import itchat
import requests
import re
from urllib import parse
from urllib.parse import urlencode
import qrcode
import json
from PIL import Image, ImageDraw, ImageFont
import time


def make_url_pic(words):
    print(23423235)

    print(words, 11111112222222)
    qr = qrcode.QRCode(
        version=2,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=1
    )  # 设置二维码的大小
    qr.add_data(words)
    qr.make(fit=True)
    img = qr.make_image()
    img.save("b.jpg")


def make_maoyan_pic(words, png_id):
    print(23423235)
    words2 = 'http://nangemaoyan.online/maoyan/%s' % png_id

    qr = qrcode.QRCode(
        version=2,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=1
    )  # 设置二维码的大小
    qr.add_data(words2)
    qr.make(fit=True)
    img = qr.make_image()
    img.save("b.jpg")


def download_pic(path, appid,token,Cookie):


    headers = {
        "Cookie": Cookie,
        "Referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=10&token=" + token + "&lang=zh_CN",
    }
    data = {
        'appid': appid,
        'path': path,
        'token': token,
        'ajax': '1',
        'f': 'json',
        'lang': 'zh_CN',
    }
    queries = urlencode(data)
    response = requests.post("https://mp.weixin.qq.com/cgi-bin/operate_appmsg?sub=weapp_qrcode", data=queries,
                             headers=headers)
    print(response.json(), 2121212)
    result_json = response.json()
    png_url = result_json.get('qrcode_url')
    print(result_json)
    response = requests.get(png_url)
    img = response.content
    with open('./' + 'a' + '.jpg', 'wb') as f:
        f.write(img)
        print('生成图片成功')


def draw_pic(FromUserName, count, name):
    t = time.localtime()
    my_time = time.strftime("%Y-%m-%d %H:%M:%S", t)
    f = "a.jpg"
    im = Image.open("a.jpg").resize((430, 430))

    draw = ImageDraw.Draw(im)  # 修改图片
    font = ImageFont.truetype('C:\Windows\Fonts\simfang.ttf', size=12)
    font2 = ImageFont.truetype('C:\Windows\Fonts\simfang.ttf', size=15)
    font3 = ImageFont.truetype('C:\Windows\Fonts\simfang.ttf', size=12)
    font4 = ImageFont.truetype('C:\Windows\Fonts\simfang.ttf', size=40)
    draw.text((0, 0), font=font2, text=name, fill=(255, 0, 0))
    draw.text((380, 20), font=font4, text=str(count), fill=(255, 0, 0))
    draw.text((315, 0), font=font3, text=my_time, fill=(255, 0, 0))

    im.save('a.jpg')
    itchat.send_image(fileDir=f, toUserName=FromUserName)


def send_mymsg(FromUserName, count, name):
    draw_pic(FromUserName, count, name)


def send_mymsgb(FromUserName, count):
    f = "b.jpg"
    itchat.send_image(fileDir=f, toUserName=FromUserName)


def send_maoyan_mymsgb(FromUserName):
    f = "b.jpg"
    itchat.send_image(fileDir=f, toUserName=FromUserName)


def store_maoyan(png_url, name_id, path, appid):
    data = {
        'png_url': png_url,
        'name': name_id,
        'path': path,
        'appid': appid,
    }
    data = json.dumps(data)
    headers = {
        "Content-Type": "application/json"
    }
    requests.post('http://180.76.96.39:8000/api/maoyan/', data=data, headers=headers)
    response = requests.get('http://180.76.96.39:8000/api/maoyan/')
    png_id = response.json()[-1].get('id')
    return png_id


def deal_user(user_dict):
    count = user_dict.get('count')
    return count


def make_user(name_id):
    data = {
        'name': name_id,

        'money': 5000,

        'vip_money': 0,

    }
    data = json.dumps(data)
    headers = {
        "Content-Type": "application/json"
    }
    is_user = requests.get('http://180.76.96.39:8000/api/users/%s/' % name_id).json()

    if is_user.get('detail') == 'Not found.':
        requests.post('http://180.76.96.39:8000/api/users/', data=data, headers=headers)
        is_user = requests.get('http://180.76.96.39:8000/api/users/%s/' % name_id).json()
        return deal_user(is_user)
    else:
        return deal_user(is_user)


def put_data(data, name_id):
    data = json.dumps(data)
    headers = {
        "Content-Type": "application/json"
    }

    requests.put('http://180.76.96.39:8000/api/users/%s/' % name_id, data=data, headers=headers)


def ref_money(name_id, money):
    data = {
        'name': name_id,
        'money': int(money),
    }
    put_data(data, name_id)


def ref_vip_money(name_id, money):
    data = {
        'name': name_id,
        'vip_money': money,
    }

    put_data(data, name_id)


def open_vip(name_id):
    data = {
        'name': name_id,
        'is_vip': 1,
    }

    data = json.dumps(data)
    headers = {
        "Content-Type": "application/json"
    }
    requests.put('http://180.76.96.39:8000/api/users/%s/' % name_id, data=data, headers=headers)


def close_vip(name_id):
    data = {
        'name': name_id,
        'is_vip': 0,
    }

    put_data(data, name_id)


def send_msg_touser(userName, name, content):
    itchat.send_msg(msg='@' + name + "----" + str(content), toUserName=userName)


def ref_count(name_id, count):
    t = time.localtime()
    print(t.tm_hour)
    if t.tm_hour == 0:
        count = 0
    data = {
        'name': name_id,
        'count': count,
    }
    put_data(data, name_id)


def ref_url(name_id, png_url):
    data = {
        'name': name_id,
        'png_url': png_url,
    }
    put_data(data, name_id)


def get_jianguo(tid, uid):
    url = 'https://api.mryitao.cn/api/marketing/coupon/thruster/assist?v=5.3.3&tk=MGE5VjAveFo1QklPZUx5RmlwOFVyWWFwdU9wYmpENDc3Y1lWMmQ4TTZCdz0%3D'
    data = {"thrusterId": tid, "userId": uid}

    header = {
        "Content-Type": "application/json"
    }
    data = json.dumps(data)
    res = requests.post(url, data=data, headers=header)
    data = res.json().get('data')

    actid = data.get('activityId')
    couid = data.get('couponId')
    return actid, couid


def not_send(words):
    if words == 'https://support.weixin.qq.com/cgi-bin/mmsupport-bin/readtemplate?t=page/common_page__upgrade&text=text001&btn_text=btn_text_0':
        return


def auto_reply(mseeages):
    url = 'http://i.itpk.cn/api.php?question=%s' % mseeages

    response = requests.get(url).text
    if mseeages == '笑话':
        response = response.encode('utf-8').decode('unicode_escape')

    return response


def send_message(msg_content, FromUserName):
    itchat.send_msg(msg=msg_content, toUserName=FromUserName)


def get_request_maoyan(path, weapp_appid):
    action = "get_wxa_code"
    __biz = "MzAxNDMyNzcyNg=="
    mid = "100000016"
    weapp_sn = "2a44c84173e6e11922d0dc0f631f2f7e"
    url = 'https://mp.weixin.qq.com/mp/appmsg_weapp'
    data = {
        'action': action,
        '__biz': __biz,
        'mid': mid,
        'weapp_sn': weapp_sn,
        'path': path,
        'weapp_appid': weapp_appid
    }
    response = requests.get(url, params=data)
    print(response.json().get('url'))
    maoyan_url = response.json().get('url')

    response = requests.get(maoyan_url)
    img = response.content
    with open('./' + 'a' + '.jpg', 'wb') as f:
        f.write(img)
        print('生成图片成功')
    return maoyan_url


def get_knife(activity_id, goods_id):
    url = 'https://bargain-movie.maoyan.com/activity/info'
    data = {
        'activity_id': activity_id,
        'goods_id': goods_id
    }
    response = requests.get(url, params=data)

    total_knives = response.json().get('data').get('activity').get('total_knives')
    print(total_knives)


def parse_url(msg,token,Cookie):
    name = msg.User['NickName']
    msg_content = msg.get('Content')
    receive_money_text = msg.get('Text')

    urls = re.findall(
        r"(([a-zA-Z]|[0-9]|[$-_@.&+]|[!*,]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)|([a-zA-Z]+.\w+\.+[a-zA-Z0-9\/_]+)",
        msg_content)
    urls = list(sum(urls, ()))
    urls = [x for x in urls if x != '']
    FromUserName = msg.get('FromUserName')
    # auto_response = auto_reply(msg_content)
    # send_message(auto_response,FromUserName)
    name_id = "".join(FromUserName.split('@'))
    count = make_user(name_id)
    if '收到转账' in receive_money_text:
        return
    if 'rjym' in msg_content:
        e = "e.jpg"
        itchat.send_image(fileDir=e, toUserName=FromUserName)
        return
    if 'pagepath' in msg_content:
        path_url = re.findall(r"<pagepath>(.+?)</pagepath>", msg_content)[0]
        title = re.findall(r"<title>(.+?)</title>", msg_content)[0]

        appid = re.findall(r"<appid>(.+?)</appid>", msg_content)[0]
        if 'CDATA' in appid:
            appid = re.findall(r"<!\[CDATA\[(.+?)\]]>", appid)[0]
        url_org = parse.unquote(path_url)  # 解码url
        path_url = re.findall(r"<!\[CDATA\[(.+?)\]]>", url_org)[0]
        print(path_url, 11111)

        if path_url == 'https://support.weixin.qq.com/cgi-bin/mmsupport-bin/readtemplate?t=page/common_page__upgrade&text=text001&btn_text=btn_text_0':
            return

        print(title, 89898798)
        jingdong_url1 = 'pages/h5/index.html?encode_url='
        jingdong_url2 = 'pages/index/index.html?open_url='
        if jingdong_url1 in path_url:
            print('京东')

            path_url = path_url.split(jingdong_url1)[1]
            make_url_pic(path_url)
            send_mymsgb(FromUserName, count)
            return
        elif jingdong_url2 in path_url:
            path_url = path_url.split(jingdong_url2)[1]
            make_url_pic(path_url)
            send_mymsgb(FromUserName, count)
            return
        print(appid)
        if '=/' in path_url:
            path_url = path_url.split('=/')[1]

            print(1)
            print(path_url)
            if 'accessfrom=share' in path_url:
                png_url = get_request_maoyan(path_url, appid)
                png_id = store_maoyan(png_url, name_id, path_url, appid)
                make_maoyan_pic(png_url, png_id)
                send_maoyan_mymsgb(FromUserName)

                return
            else:
                if count:
                    count += 1
                else:
                    count = 1
                ref_count(name_id, count)
                download_pic(path_url, appid,token,Cookie)
                send_mymsg(FromUserName, count, name)
        else:
            print(2)

            if '.html?' in path_url:

                path_list = path_url.split('.html?')

                path_url1 = path_list[0]
                path_url2 = path_list[1]
                path_url = path_url1 + '?' + path_url2

                if path_url[0] == "/":
                    path_url = path_url[1::]
                myurl = re.finditer('=', path_url)
                my_list = []
                for i in myurl:
                    i.group()
                    myplace = i.span()
                    my_list.append(path_url[myplace[1]::])
                path_url_list = path_url.split(my_list[0])[0]
                path_url3 = parse.quote(my_list[0])
                path_url4 = path_url_list + path_url3

                if '快来帮我点一点，爱你哦' in msg_content:
                    jianguo_list = parse.unquote(path_url4).split('&')
                    tid = jianguo_list[1].split('=')[1]
                    uid = jianguo_list[2].split('=')[1]
                    tid, uid = get_jianguo(tid, uid)
                    print(tid, uid)
                    left_url = '://api.mryitao.cn/active/couponHelp?activityId=' + str(tid) + '&couponId=' + str(
                        uid) + '&type=0&wxcard=1'
                    left_url = parse.quote(parse.quote(left_url))
                    path_url = 'pages/webView/webView?url=https' + left_url
                    print(left_url)
                    download_pic(path_url, appid,token,Cookie)
                if '?url=' in path_url4:
                    print(5555)
                    download_pic(path_url4, appid,token,Cookie)
                else:
                    print(6666)
                    download_pic(path_url, appid,token,Cookie)
                if count:
                    count += 1
                else:
                    count = 1
                ref_count(name_id, count)
                send_mymsg(FromUserName, count, name)
            elif '.html' in path_url:
                path_list2 = path_url.split('.html')[0]
                if count:
                    count += 1
                else:
                    count = 1
                ref_count(name_id, count)
                download_pic(path_list2, appid,token,Cookie)
                send_mymsg(FromUserName, count, name)
        print('----------------')
    elif 'http' in msg_content or 'www.' in msg_content or 'com/' in msg_content:
        if '<url>' not in msg_content:
            print(12121212)
            if count:
                count += 1
            else:
                count = 1
            ref_count(name_id, count)
            if urls[
                0] == 'https://support.weixin.qq.com/cgi-bin/mmsupport-bin/readtemplate?t=page/common_page__upgrade&text=text001&btn_text=btn_text_0':
                return
            make_url_pic(urls[0])
            send_mymsgb(FromUserName, count)
        else:
            msg_content = msg['Url']
            if 'hash' in msg_content:
                url = msg_content.replace('amp;', '')
                msg_content = url.split('hash')[0]
                msg_content = msg_content + '_form=web'
            if 'amp;' in msg_content:
                msg_content = msg_content.replace('amp;', '')
            if count:
                count += 1
            else:
                count = 1
            ref_count(name_id, count)
            if msg_content == 'https://support.weixin.qq.com/cgi-bin/mmsupport-bin/readtemplate?t=page/common_page__upgrade&text=text001&btn_text=btn_text_0':
                return
            make_url_pic(msg_content)
            send_mymsgb(FromUserName, count)
    elif '/' in urls:
        if count:
            count += 1
        else:
            count = 1
        ref_count(name_id, count)
        if urls[
            0] == 'https://support.weixin.qq.com/cgi-bin/mmsupport-bin/readtemplate?t=page/common_page__upgrade&text=text001&btn_text=btn_text_0':
            return

        make_url_pic(urls[0])
        send_mymsgb(FromUserName, count)


def get_money(name_id):
    user = requests.get('http://180.76.96.39:8000/api/users/%s/' % name_id)
    if user.status_code == 200:
        user_money = user.json().get('money')
        return user_money


def delete_code(codename):
    print(codename, 222222)
    requests.delete('http://180.76.96.39:8000/api/users2/%s/' % codename)


def congzhi(codename, name_id):
    is_user = requests.get('http://180.76.96.39:8000/api/users2/%s/' % codename)
    if is_user.status_code == 200:
        num = is_user.json().get('codenum')
        print(num)
        delete_code(codename)
        user = requests.get('http://180.76.96.39:8000/api/users/%s/' % name_id)
        if user.status_code == 200:
            vip_money = user.json().get('vip_money')
            print(vip_money)
            money = vip_money + num
            print(money)
            ref_vip_money(name_id, money)
            return money
    else:
        return 'a404'
